﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using doru;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;

namespace BrainWash
{
    public class Program
    {
        static void Main(string[] args)
        {
            Spammer3.Setup();
            new Program();   
        }
        public Program()
        {
            MatchCollection ms = Regex.Matches(File.ReadAllText("Ips.txt"), "/(.+?);(.+?);(.+)\r");
            foreach (Match m in ms)
            {
                BrainWash _BrainWash = new BrainWash { host = m.Groups[1].Value, port = int.Parse(m.Groups[2].Value), page = m.Groups[3].Value };
                _BrainWash.StartAsync();
            }
        }
    }

    public class BrainWash
    {
        public string host;
        public int port;
        public string page;
        NetworkStream ns;
        public void StartAsync()
        {
            new Thread(Start).Start();
        }
        private void  Start()
        {
            Connect();
        test:
            string file = (name + DateTime.Now.ToString().Replace(":", ".") + ".mp3").Trace();
            using (FileStream _FileStream = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                while (true)
                {
                    try
                    {

                        _FileStream.Write(ns.Read(1024 * 50));
                        _FileStream.Flush();
                        if (_FileStream.Length > 3000 * 1024) goto test;                        
                    }
                    catch (IOException) { Connect();}
                }
            }
            throw new Exception("exit");
        }
        public string name;
        private Socket Connect()
        {
            while(true)
                try
                {
                    Socket _Socket = new TcpClient(host, port).Client;
                    string s = Res.get.Replace("_host_", host + ":" + port).Replace("_page_", page);
                    _Socket.Send(s);
                    ns = new NetworkStream(_Socket);
                    ns.ReadTimeout = 20000;
                    string s2 = ns.Cut("\r\n\r\n").ToStr();
                    name = Regex.Match(s2, "icy-name:(.+)\r").Groups[1].Value;
                    return _Socket;
                }
                catch { }
        }
    }
}
